#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试 ChromaDB 中存储的对话 ID 格式
"""

import asyncio
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from src.config import load_config
from src.database.manager import DatabaseManager

async def debug_chromadb_conversation_ids():
    """调试 ChromaDB 中的对话 ID 格式"""
    
    # 加载配置
    config = load_config()
    
    # 初始化数据库管理器
    db_manager = DatabaseManager(config)
    await db_manager.initialize()
    
    try:
        print("=== ChromaDB 对话 ID 格式调试 ===")
        
        # 1. 获取 ChromaDB 中的所有对话记录
        print("\n1. 获取 ChromaDB conversations 集合中的所有记录...")
        
        chromadb_client = db_manager.chromadb_client
        
        # 获取 conversations 集合
        try:
            conversations_collection = chromadb_client.client.get_collection("conversations")
            
            # 获取所有记录
            all_conversations = conversations_collection.get()
            
            print(f"   找到 {len(all_conversations['ids'])} 条对话记录")
            
            # 显示前10条记录的ID和元数据
            for i, (conv_id, metadata) in enumerate(zip(all_conversations['ids'][:10], all_conversations['metadatas'][:10])):
                print(f"   记录 {i+1}:")
                print(f"     ID: {conv_id}")
                print(f"     元数据: {metadata}")
                print()
                
        except Exception as e:
            print(f"   ❌ 获取 ChromaDB conversations 集合失败: {e}")
        
        # 2. 获取 MongoDB 中的对话记录
        print("\n2. 获取 MongoDB conversations 集合中的记录...")
        
        mongodb_client = db_manager.mongodb_client
        
        try:
            collection = mongodb_client.get_collection('conversations')
            
            # 获取前10条记录
            cursor = collection.find({}).limit(10)
            
            conversations = []
            async for doc in cursor:
                conversations.append(doc)
            
            print(f"   找到 {len(conversations)} 条对话记录（显示前10条）")
            
            for i, conv in enumerate(conversations):
                print(f"   记录 {i+1}:")
                print(f"     _id: {conv.get('_id')}")
                print(f"     conversation_id: {conv.get('conversation_id')}")
                print(f"     title: {conv.get('title', 'N/A')}")
                print(f"     user_id: {conv.get('user_id', 'N/A')}")
                print()
                
        except Exception as e:
            print(f"   ❌ 获取 MongoDB conversations 集合失败: {e}")
        
        # 3. 检查ID匹配情况
        print("\n3. 检查 ID 匹配情况...")
        
        try:
            # 获取ChromaDB中的所有ID
            chromadb_ids = set(all_conversations['ids'])
            
            # 获取MongoDB中的所有conversation_id和_id
            mongodb_collection = mongodb_client.get_collection('conversations')
            cursor = mongodb_collection.find({})
            
            mongodb_conversation_ids = set()
            mongodb_object_ids = set()
            
            async for doc in cursor:
                if 'conversation_id' in doc:
                    mongodb_conversation_ids.add(doc['conversation_id'])
                mongodb_object_ids.add(str(doc['_id']))
            
            print(f"   ChromaDB 中的 ID 数量: {len(chromadb_ids)}")
            print(f"   MongoDB 中的 conversation_id 数量: {len(mongodb_conversation_ids)}")
            print(f"   MongoDB 中的 _id 数量: {len(mongodb_object_ids)}")
            
            # 检查匹配情况
            conversation_id_matches = chromadb_ids.intersection(mongodb_conversation_ids)
            object_id_matches = chromadb_ids.intersection(mongodb_object_ids)
            
            print(f"   ChromaDB ID 与 MongoDB conversation_id 匹配数量: {len(conversation_id_matches)}")
            print(f"   ChromaDB ID 与 MongoDB _id 匹配数量: {len(object_id_matches)}")
            
            if conversation_id_matches:
                print(f"   匹配的 conversation_id 示例: {list(conversation_id_matches)[:5]}")
            
            if object_id_matches:
                print(f"   匹配的 _id 示例: {list(object_id_matches)[:5]}")
            
            # 显示不匹配的ID
            unmatched_chromadb = chromadb_ids - mongodb_conversation_ids - mongodb_object_ids
            if unmatched_chromadb:
                print(f"   ChromaDB 中无法在 MongoDB 中找到的 ID 数量: {len(unmatched_chromadb)}")
                print(f"   示例: {list(unmatched_chromadb)[:5]}")
                
        except Exception as e:
            print(f"   ❌ 检查 ID 匹配失败: {e}")
        
    finally:
        # 清理资源
        await db_manager.close()
        print("\n=== 调试完成 ===")

if __name__ == "__main__":
    asyncio.run(debug_chromadb_conversation_ids())